package com.xishu.https;


import com.xishu.config.Config;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;

@Configuration
public class MultiConnectionSupport {
    private static Logger logger = LoggerFactory.getLogger(MultiConnectionSupport.class);

    /**
     * 创建SSL链接
     *
     * @return
     */
    private Connector createSslConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Http11NioProtocol protocolHandler = (Http11NioProtocol) connector.getProtocolHandler();

        try {
            String keystoreFileName = "3g48.jks";
            File keyStoreFile = new File(Config.loadConfigPath() + "/" + keystoreFileName);;
            connector.setScheme("https");
            connector.setPort(443);
            connector.setSecure(true);
            protocolHandler.setSSLEnabled(true);
            protocolHandler.setKeystoreFile(keyStoreFile.getAbsolutePath());
            logger.info("keystore path  is {}", keyStoreFile.getAbsolutePath());
            protocolHandler.setKeystorePass("gAXRU3ia");
            protocolHandler.setKeyAlias("alias-key");
        } catch (Exception e) {
            logger.error("", e);
        }
        return connector;
    }

    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
            }
        };

        tomcat.addAdditionalTomcatConnectors(createSslConnector());
        return tomcat;
    }

}

